package com.james.customcamera.base;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.james.customcamera.CustomCameraApplication;
import com.james.customcamera.mvp.IView;

import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements IView, View.OnClickListener {
    protected P mPresenter;
    protected View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(getLayoutId(), null);
        ButterKnife.bind(this, root);
        mPresenter = loadPresenter();
        initCommonData();
        initData();
        initView();
        return root;
    }

    protected abstract void initView();

    protected abstract int getLayoutId();

    protected abstract P loadPresenter();

    private void initCommonData() {
        if (mPresenter != null) {
            mPresenter.attachView(this);
        }
    }

    protected abstract void initData();

    protected abstract void otherViewClick(View view);


    /**
     * @return 显示的内容
     */
    public View getView() {
        view = View.inflate(CustomCameraApplication.getContext(), getLayoutId(), null);
        return view;
    }

    /**
     * 点击的事件的统一的处理
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            default:
                otherViewClick(view);
                break;
        }
    }

    /**
     * 显示一个内容为str的toast
     *
     * @param str
     */
    public void toast(String str) {
        Toast.makeText(CustomCameraApplication.getContext(), str, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }
}
